package oppsa.view;

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.URISyntaxException;
import java.util.Set;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

import oppsa.controller.Properties;
import oppsa.controller.Translate;
import oppsa.util.Constants;

import org.jdesktop.swingx.JXFrame;
import org.jdesktop.swingx.JXFrame.StartPosition;

import sun.jvmstat.monitor.HostIdentifier;
import sun.jvmstat.monitor.MonitorException;
import sun.jvmstat.monitor.MonitoredHost;
import sun.jvmstat.monitor.MonitoredVm;
import sun.jvmstat.monitor.MonitoredVmUtil;
import sun.jvmstat.monitor.VmIdentifier;


public class MainApplication {

	
	public static void main(String[] args) throws URISyntaxException 
	{
		RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();  
			final int runtimePid = Integer.parseInt(rt.getName().substring(0,rt.getName().indexOf("@")));  
								 
			java.awt.EventQueue.invokeLater(new Runnable() {  
				@Override
				public void run() {  
				Translate t = new Translate();
				 // If exists another instance, show message and terminates the current instance.  
				 // Otherwise starts application.  
				 if (getMonitoredVMs(runtimePid))  
				 {  
					/*InterfaceConnection cnx2 = ConnectionFactory.getConnection(Constants.MYSQL);
					Boolean connexion2 = cnx2.connectOpenCheck();
					InterfaceConnection cnx1 = ConnectionFactory.getConnection(Constants.HSQLDB);
					Boolean connexion1 = cnx1.connectOpenCheck();
					cnx2.connectClose();
					cnx1.connectClose();
					if (connexion2 && connexion1)
					{*/
					 Properties prop = new Properties();
	    			prop.loadProperties(Constants.config_path);
	    			prop.setProperties("path", System.getProperty("user.dir"), Constants.config_path);
					JXFrame authentificationView = new AuthentificationView();
					
					authentificationView.setSize(300, 150);
					authentificationView.setLocationRelativeTo(null);
					authentificationView.setResizable(false);
					authentificationView.setStartPosition(StartPosition.CenterInScreen);
					authentificationView.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
					((AuthentificationView) authentificationView).placeComponents();
			
					authentificationView.setVisible(true);
					//JXFrame homeView = new HomeView();
					//homeView.setVisible(true);
						
						
					/*}
					else
					{		
						 // for copying style
					JLabel label = new JLabel();
					Font font = label.getFont();
					
					// create some css from the label's font
					

					URI uri = null;
					try {
						uri = new URI("http://my-cobalt.net/Client/fr/contact.aspx");
					} catch (URISyntaxException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					StringBuffer style = new StringBuffer("font-family:" + font.getFamily() + ";");
					style.append("font-weight:" + (font.isBold() ? "bold" : "normal") + ";");
					style.append("font-size:" + font.getSize() + "pt;");
					// html content
					JEditorPane ep = new JEditorPane("text/html", "<html><body style=\"" + style + "\">" //
					    + t.getLocalizedText("errorCon1")+" :  <a href=\""+uri+"\">my-cobalt.net</a>" //
					    + "</body></html>");
					
					// handle link events
					ep.addHyperlinkListener(new HyperlinkListener()
					{
					    @Override
					    public void hyperlinkUpdate(HyperlinkEvent e)
					    {
					        if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
					        	try {
									Desktop.getDesktop().browse(e.getURL().toURI());
								} catch (IOException | URISyntaxException e1) {
									// TODO Auto-generated catch block
								e1.printStackTrace();
							}
						} // roll your own link launcher or use Desktop if J6+
					    }
					});
					ep.setEditable(false);
					ep.setBackground(label.getBackground());
					
					// show
					    JOptionPane.showMessageDialog(null, ep);
					}*/
			 	} else {
						JOptionPane.showMessageDialog(null,t.getLocalizedText("errorCon2"));
				}  
		  				   
		  			 }  
		  		 });

		}
	
	private static boolean getMonitoredVMs(int processPid) {  
	 		 MonitoredHost host;  
	 		 Set vms;  
	 		 try {  
	 			 host = MonitoredHost.getMonitoredHost(new HostIdentifier((String)null));  
	 			 vms = host.activeVms();  
	 		 } catch (java.net.URISyntaxException sx) {  
	 			 throw new InternalError(sx.getMessage());  
	 		 } catch (MonitorException mx) {  
	 			 throw new InternalError(mx.getMessage());  
	 		 }  
	 		 MonitoredVm mvm = null;  
	 		 String processName = null;  
	 		 try{  
	 			 mvm = host.getMonitoredVm(new VmIdentifier(String.valueOf(processPid)));  
	 			 processName = MonitoredVmUtil.commandLine(mvm);  
	 			 processName = processName.substring(processName.lastIndexOf("\\") + 1,processName.length());  
	 			 mvm.detach();  
	 		 } catch (Exception ex) {  
	 			   
	 		 }  

	 		 for (Object vmid: vms) {  
	 			 if (vmid instanceof Integer) {  
	 				 int pid = ((Integer) vmid).intValue();  
	 				 String name = vmid.toString(); // default to pid if name not available  
	 				 try {  
	 					  mvm = host.getMonitoredVm(new VmIdentifier(name));  
	 					  // use the command line as the display name  
	 					  name =  MonitoredVmUtil.commandLine(mvm);  
	 					  name = name.substring(name.lastIndexOf("\\")+1,name.length());  
	 					  mvm.detach();  
	 					  if ((name.equalsIgnoreCase(processName)) && (processPid != pid)) {
							return false;
						}  
	 				 } catch (Exception x) {  
	 					  // ignore  
	 				 }  
	 			 }  
	 		 }  
	 		   
	 		 return true;  
	  }

	
	
}
